<!DOCTYPE html>
<html lang="en">
<head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Document</title>
      <style>
            #box,#box2{
                  width: 100px;
                  height: 100px;
                  background: skyblue;
                  position: absolute;
                  left: 0;
                  top : 0;
            }
            #box2{
                  background: springgreen;
                  left: 200px;
            }
      </style>
</head>
<body>
      <div id="box"></div>
      <div id="box2"></div>

      <script>
          

            function Drag( selector ){
                  // 拖拽的元素;
                  this.ele = document.querySelector(selector);
                  this.bindEvent();
            }
            // tip : 方法分割是没有逗号的;
            Drag.prototype.bindEvent = function(){
                  var self = this;
                  self.ele.onmousedown = function(evt){
                        // 拖拽开启;
                        // console.log("拖拽开启");
                        let e = evt || event;
                        // 获取 offsetX 和 offsetY;
                        let { offsetX : x , offsetY : y } = e;
                        document.onmousemove = function(evt){
                              let e = evt || event;
                              // 拖拽进行中;
                              // console.log("拖拽进行中");
                              // 为了让元素跟着鼠标点击的位置走而不是跟着鼠标的client 走;
                              self.eleMove( e.clientX - x , e.clientY - y);
                        }
                  }
                  this.ele.onmouseup = function( ){
                        // console.log("拖拽结束");
                        document.onmousemove = null;
                  }
            }
            Drag.prototype.eleMove = function( x , y ){
                  this.ele.style.left = x + "px";
                  this.ele.style.top  = y + "px";
            }

            function BoundaryDrag(selector){
                  var son_ins = this;
                  Drag.call(son_ins , selector);
            }
            for(var attr in Drag.prototype){
                  BoundaryDrag.prototype[attr] = Drag.prototype[attr];
            }
            // 使用的时候注意下 : 如果在构造函数里面有方法的调用，那么请把调用放在继承之后。

            BoundaryDrag.prototype.eleMove = function( x , y ){

                  x = x < 0 ? 0 : x;

                  this.ele.style.left = x + "px";
                  this.ele.style.top  = y + "px";
            }

            var drag = new BoundaryDrag("#box");

      </script>
</body>
</html>